package HashBuck;

public class HashBuck {
    class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    private Node[] array;
    private int usedSize;

    private static final float DEFAULT_LOAD_FACTOR = 0.75f;

    public HashBuck() {
        this.array = new Node[10];
    }

    public void put(int key, int val)
    {
        int index = key % array.length;

        Node cur = array[index];
        while (cur != null)
        {
            if(cur.key == key)
            {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        Node node = new Node(key, val);
        node.next = this.array[index];
        this.array[index] = node;
        usedSize++;
        if(doLoadFactor() > DEFAULT_LOAD_FACTOR)
        {
            resize();
        }
    }

    private void resize() {
        Node[] newArray = new Node[2 * array.length];

        for(int i = 0; i < array.length; i++)
        {
            Node cur = array[i];
            while(cur != null)
            {
                Node tmp = cur.next;
                int newIndex = cur.key % newArray.length;

                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = tmp;
            }
        }
        this.array = newArray;
    }

    private float doLoadFactor() {
        return usedSize * 1.0f / array.length;
    }

    public int get(int key)
    {
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null)
        {
            if(cur.key == key)
            {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}

